package me.yuxiaoyao.util.treeify;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author kerryzhang on 2020/10/30
 *
 *
 * default Mapper 依赖 Spring，如果没有Spring，请自定义Mapper
 */

public class DefaultTreeMapper<S, T> implements ITreeMapper<S, T> {

    private static Class<?> beanUtilsClass;
    private static Method copyPropertiesMethod;
    private static volatile DefaultTreeMapper instance;

    static {
        try {
            beanUtilsClass = Class.forName("org.springframework.beans.BeanUtils");
            /// BeanUtils.copyProperties(source, target);
            copyPropertiesMethod = beanUtilsClass.getDeclaredMethod("copyProperties", Object.class, Object.class);
            copyPropertiesMethod.setAccessible(true);
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            // no spring framework can not use default mapper
            // e.printStackTrace();
        }
    }


    public static <S, T> DefaultTreeMapper<S, T> getInstance() {
        if (copyPropertiesMethod == null) {
            throw new IllegalStateException("can not use default mapper cause default mapper dependency spring framework,please check has spring or custom mapper");
        }
        if (instance == null) {
            synchronized (DefaultTreeMapper.class) {
                if (instance == null) {
                    instance = new DefaultTreeMapper<>();
                }
            }
        }
        //noinspection unchecked
        return instance;
    }

    @Override
    public void mapper(S source, T target) {
        try {
            copyPropertiesMethod.invoke(beanUtilsClass, source, target);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e.getCause());
        }
    }
}
